package com.huawei.esdk.uc.sametime.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.wb.swt.SWTResourceManager;

import com.huawei.esdk.uc.jna.struct.STTime;
import com.huawei.esdk.uc.jna.util.StringUtil;
import com.huawei.esdk.uc.sametime.ConstantsDefines;
import com.huawei.esdk.uc.sametime.EsdkPluginActivator;
import com.huawei.esdk.uc.sametime.preferences.PreferenceConstants;
import com.ibm.collaboration.realtime.contacts.search.DirectoryInfo;
import com.ibm.collaboration.realtime.people.Person;

public class PluginUtil
{
    private static Logger logger = Logger.getLogger(PluginUtil.class);

    public static boolean isUCConfig()
    {
        IPreferenceStore preferenceStore = EsdkPluginActivator.getDefault()
                .getPreferenceStore();
        String userName = preferenceStore
                .getString(PreferenceConstants.P_USERNAME);
        String password = preferenceStore
                .getString(PreferenceConstants.P_PASSWORD);
        String ucSvrIp = preferenceStore
                .getString(PreferenceConstants.P_UCSVRIP);
        int port = preferenceStore.getInt(PreferenceConstants.P_PORT);

        logger.info("preferenceStore UC info:" + userName + ", and ucSvrIp:"
                + ucSvrIp + ", and port:" + port);

        if (!StringUtil.isEmptyStr(userName)
                && !StringUtil.isEmptyStr(password)
                && !StringUtil.isEmptyStr(ucSvrIp))
        {
            return true;
        }
        return false;
    }

    /**
     * 验证电话号码是否合法
     * @param phoneNumber 一位或多位0-9之间的整数
     * @return 验证成功返回true，验证失败返回false
     */
    public static boolean checkTelephone(String phoneNumber)
    {
        String regex = "\\d*";
        return Pattern.matches(regex, phoneNumber);
    }

    /**
     * 从contactid获取对应的uc账号
     * sametime联系人Person对象的contactid,id字段都是一长串uid=gaomingok@126.com
     * ,cn=testusers,o=testorg,dc=greenhouse,dc=ibm,dc=com::st1797591543
     * 这种字符串,需要做转换才能获取对应的uc账号
     * @param uid
     * @return 对应的uc账号
     */
    public static String getUCAccountFromContactID(String uid)
    {
        String ucAccount = null;
        if (!StringUtil.isEmptyStr(uid))
        {
            /*
             * 注意,从sametime中获取到的personid,即uid为uid=gaomingok@126.com,cn=testusers,
             * o=testorg
             * ,dc=greenhouse,dc=ibm,dc=com::st1797591543这个字段是不能直接用在会议中的
             */
            // int startIndex = 4;
            // int endIndex = uid.indexOf("@");
            // return uid.substring(startIndex, endIndex);
            int startIndex = 3;
            int endIndex = uid.indexOf('/');

            try
            {
                ucAccount = uid.substring(startIndex, endIndex);
            }
            catch (IndexOutOfBoundsException exception)
            {

                ucAccount = "";
                logger.error(exception.getMessage());
                logger.error("set ucAccount empty string");
            }

        }
        return ucAccount;
    }

    public static String getFormatTime(int duration)
    {
        if (duration < 0)
        {
            duration = 0;
        }
        int hour = duration / (60 * 60);
        int min = (duration % (60 * 60)) / 60;
        int second = duration % 60;
        DecimalFormat format = new DecimalFormat("00");
        return String.format("%s:%s:%s", format.format(hour), format
                .format(min), format.format(second));
    }

    public static String getFormatDate(STTime time)
    {
        DecimalFormat format = new DecimalFormat("00");
        return String.format("%s/%s/%s %s:%s:%s", format.format(time.year),
                format.format(time.month), format.format(time.day), format
                        .format(time.hour), format.format(time.minute), format
                        .format(time.second));
    }

    public static String getLocalUcAccount()
    {
        IPreferenceStore preferenceStore = EsdkPluginActivator.getDefault()
                .getPreferenceStore();
        String userName = preferenceStore
                .getString(PreferenceConstants.P_USERNAME);
        return userName;
    }

    /**
     * 判断输入到被叫号码输入框中的字符是不是合法的
     * @param inputChar
     * @return 如果是数字,*,#,则是合法,否则不是
     */
    public static boolean isValidInput(final char inputChar)
    {

        if ('*' == inputChar || '#' == inputChar)
        {
            return true;
        }
        if (inputChar >= '0' && inputChar <= '9')
        {
            return true;
        }
        return false;
    }

    public static Font getFontMicrosoftYahei()
    {
        return SWTResourceManager.getFont(
                ConstantsDefines.FONT_MICROSOFT_YAHEI, 16, SWT.NORMAL);
    }

    public static Object getPersonProperty(Person person, String propertyKey)
    {
        Object propertyValue = null;
        if (null != person && !StringUtil.isEmptyStr(propertyKey))
        {
            DirectoryInfo directInfo = person.getDirectoryInfo();
            if (null != directInfo)
            {
                propertyValue = directInfo.get(propertyKey);
            }
        }
        return propertyValue;
    }

    public static String getLog4jPath()
    {
        File file = new File(PluginUtil.class.getProtectionDomain()
                .getCodeSource().getLocation().getPath());
        return file.getAbsolutePath();
    }

    /**
     * 设置jna所需的dll库的搜索路径,但因为UC的dll库内部之间有互相引用关系 且它们之间的搜索路径是系统变量PATH中指定的,所以,此方法失效了
     * @param path
     */
    public static void setJNALibPath(String path)
    {
        if (!StringUtil.isEmptyStr(path))
        {
            System.setProperty("jna.library.path", path);
        }
        else
        {
            logger.error("JNA lib search path is null or empty");
        }
    }

    public static void confiLog4jProperties()
    {
        Properties log4jproperties = new Properties();
        String log4jFileName = getLog4jPath() + File.separator
                + "log4j.properties";

        InputStream log4jInputStream = null;
        try
        {
            log4jInputStream = new FileInputStream(log4jFileName);
            log4jproperties.load(log4jInputStream);
            if (!log4jproperties.isEmpty())
            {
                String logName = getLog4jPath() + File.separator + "log"
                        + File.separator + "esdk_uc_sametime_plugin.log";
                log4jproperties.setProperty("log4j.appender.fileLogger.File",
                        logName);
                PropertyConfigurator.configure(log4jproperties);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            logger.error(e.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
            logger.error(e.toString());
        }
        finally
        {
            if (null != log4jInputStream)
            {
                try
                {
                    log4jInputStream.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                    logger.error(e.toString());
                }
                finally
                {
                    log4jInputStream = null;
                }
            }
        }
    }

}
